﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace PhysicsSimulator.Game.DapKeo
{
    public partial class CandyGamePage : PhoneApplicationPage
    {
        private const int NUM_HIT = 8;

        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;
        UIElementRenderer elementRenderer;

        CBird _blueBird;
        CBird _yellowBird;
        CControlBird _controlBird;
        CPig _pig;

        SpriteFont _scoreFont;
        int _score = 0;
        int _tempScore = 0;
        int _hit_remain = NUM_HIT;
        CSprite _hitSprite;

        public CandyGamePage()
        {
            InitializeComponent();

            contentManager = (Application.Current as App).Content;

            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += timer_Update;
            timer.Draw += timer_Draw;

            LayoutUpdated += CandyGamePage_LayoutUpdated;

            AudioManager.PlaySound("CandyMusic", true);
        }

        void CandyGamePage_LayoutUpdated(object sender, EventArgs e)
        {
            if (ActualWidth == 0 || ActualHeight == 0)
                return;

            // see if we already have the right sized renderer
            if (elementRenderer != null &&
                elementRenderer.Texture != null &&
                elementRenderer.Texture.Width == (int)ActualWidth &&
                elementRenderer.Texture.Height == (int)ActualHeight)
            {
                return;
            }

            // dispose the current renderer
            if (elementRenderer != null)
                elementRenderer.Dispose();

            // create the renderer
            elementRenderer = new UIElementRenderer(LayoutRoot, (int)ActualWidth, (int)ActualHeight);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            _controlBird = new CControlBird(spriteBatch);
            _controlBird.BirdTexture = new CSprite(contentManager.Load<Texture2D>("Images/CandyGame/bird-3"));
            _controlBird.ShaderTexture = new CSprite(contentManager.Load<Texture2D>("Images/CandyGame/bird-shadow-3"));
            _controlBird.Position = new Vector2(650.0f,425.0f);
            _controlBird.Init(contentManager);

            _yellowBird = new CBird(spriteBatch);
            _yellowBird.BirdTexture = new CSprite(contentManager.Load<Texture2D>("Images/CandyGame/bird-1"));
            _yellowBird.ShaderTexture = new CSprite(contentManager.Load<Texture2D>("Images/CandyGame/bird-shadow-1"));
            _yellowBird.Position = new Vector2(200.0f,445.0f);
            _yellowBird.Init(contentManager);

            _blueBird = new CBird(spriteBatch);
            _blueBird.BirdTexture = new CSprite(contentManager.Load<Texture2D>("Images/CandyGame/bird-2"));
            _blueBird.ShaderTexture = new CSprite(contentManager.Load<Texture2D>("Images/CandyGame/bird-shadow-2"));
            _blueBird.Position = new Vector2(65.0f,400.0f);

            _blueBird.Init(contentManager);

            _pig = new CPig(spriteBatch);
            _pig.Init(contentManager);

            _scoreFont = contentManager.Load<SpriteFont>("Images/CandyGame/ScoreFont");
            _hitSprite = new CSprite(contentManager.Load<Texture2D>("Images/CandyGame/sticks-small"));

            timer.Start();
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            timer.Stop();
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);
            AudioManager.StopSound("CandyMusic");
            base.OnNavigatedFrom(e);
        }

        void timer_Update(object sender, GameTimerEventArgs e)
        {
            _yellowBird.Update(e);
            _blueBird.Update(e);
            _controlBird.Update(e);
            _pig.Update(e);

            if (_controlBird.CurrentBirdState == ControlBirdState.BEAT)
            {
                if(_pig.CheckIntersectPoint(_controlBird.GetSticksPoint()))
                {
                    _pig.Hit(_controlBird.GetForce());
                    _score += (int)(_controlBird.GetForce() * 20);
                }
            }

            if (_tempScore < _score)
                _tempScore += 1;

            if (_pig.CandyRemain == 0 && _hit_remain == 0 && _controlBird.CurrentBirdState == ControlBirdState.IDLE)
            {
                System.Windows.MessageBox.Show("Chúc mừng! Bạn được " + _score.ToString() + " điểm!", "KẾT QUẢ CỦA BẠN", MessageBoxButton.OK);
                //reset game
                _tempScore = 0;
                _score = 0;
                _hit_remain = NUM_HIT;
                _pig.Reset();
                
            }
        }

        void timer_Draw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.White);
            elementRenderer.Render();
            spriteBatch.Begin();
            spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);
            _blueBird.Draw(e);               
            _pig.Draw(e);
            _yellowBird.Draw(e);
            _controlBird.Draw(e);
            spriteBatch.DrawString(_scoreFont,"Score: "+_tempScore.ToString(),new Vector2(20,5),Color.White);
            Vector2 position = new Vector2(775, 20);
            for (int i = 0; i < _hit_remain; i++)
            {
                spriteBatch.Draw(_hitSprite.Texture, position, null, Color.White, 0, _hitSprite.Origin, 1, SpriteEffects.None, 0);
                position.X -= _hitSprite.Width;
            }
            spriteBatch.End();
        }

        protected override void OnTap(System.Windows.Input.GestureEventArgs e)
        {
            base.OnTap(e);

            if (_hit_remain > 0 && _controlBird.Beat())
            {
                _hit_remain -= 1;
            }            
        }
    }
}